package com.metadata_system.access_provider.request;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import tk.mybatis.mapper.entity.Example;
import com.metadata_system.common.utils.MyUtil;

import java.util.Arrays;
import java.util.List;

@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class MemberListParams {
    Integer accessProviderId;
    Integer userId;
    Integer status;
    String username;
    String createdTime;
    // 查询-起始值
    public Integer page;
    // 查询-条数
    public Integer pageSize;
    // 排序-字段类型
    public String sortProp;
    // 排序-字段
    public String sortOrder;

    public RowBounds getRowRunds(){
        // 限制错误分页数
        if (this.getPage()==null || this.getPage()<=0){
            this.setPage(1);
        }
        // 限制查询1000条
        if (this.getPageSize()==null || this.getPageSize()<=0 || this.getPageSize()>1000){
            this.setPageSize(10);
        }
        int offset = (this.getPage() - 1) * this.getPageSize();
        return new RowBounds(offset, this.getPageSize());
    }

    public void setConditionTime(String timeArrString, Example.Criteria criteria, String field){
        if (StringUtils.isBlank(timeArrString)){
            return;
        }
        String[] timeArr = MyUtil.formatDateArr(timeArrString);
//        System.out.println("timeArr: "+ JSON.toJSONString(timeArr));
        if (timeArr!=null){
            if (!StringUtils.isBlank(timeArr[0])){
                criteria.andGreaterThanOrEqualTo(field,timeArr[0]);
            }
            if (!StringUtils.isBlank(timeArr[1])){
                criteria.andLessThanOrEqualTo(field,timeArr[1]);
            }
        }
    }

    public void setOrder(Example example, List<String> allowFields){
        if (allowFields.contains(this.getSortProp())){
            if (StringUtils.isBlank(this.getSortOrder())){
                this.setSortOrder("DESC");
            }
            String prop = MyUtil.humpToLine(this.getSortProp());
            example.setOrderByClause(prop+" "+this.getSortOrder());
        }
    }

    public void setOrder(Example example, String allowFieldsString){
        setOrder(example, Arrays.asList(allowFieldsString.split(",")));
    }
}
